import json

from flask import jsonify, request, g
from app.db.models.notifications import Notifications
from app.libs.redprint import RedPrint
from app.handler.v2_mail import Mail
from app.log.logs import UMailLog

api = RedPrint('mail')


@api.route('/<string:mail_type>/get/<string:mode>', methods=["GET"])
def get_mails_warnings(mail_type, mode):
    return jsonify({'code': 200, 'msg': 'ok', 'results': {mail_type: Mail(mail_type, mode).get()}})


@api.route('/mark', methods=['POST'])
def mark_mail():
    request_args = json.loads(request.data)
    mail_ids = request_args.get('mail_ids', [])

    mark = True
    uid = g.user.id
    mails = Notifications.objects.filter(pk__in=mail_ids, to=uid)

    if not (count := len(mails)):
        return jsonify({'code': 200, 'msg': 'ok'})

    query = {
        f'isMarkedMap__{uid}': mark
    }
    for mail in mails:
        mail.update(**query)

        # 当所有人都阅读完成时, 标记为整个消息为已读
        mail.isMarkedMap[str(uid)] = mark
        if set(mail.isMarkedMap.values()) == {True}:
            mail.update(isMarked=True)

    # mark_zh_cn = '已读' if mark else '未读'
    UMailLog().info(
        action_message='更新消息状态',
        detail=f"读取{count}条告警消息。"
    )

    return jsonify({'code': 200, 'msg': 'ok'})
